#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 14 23:14:26 2019

@author: jili
"""
from jili.core import keyword
from jili.core import moheengine as mh
from jili.core.printlog import print
from jili.price.getdata import gettick
import json,os
from jili.tool.state import ismongo,isredis,telnet,check_process,get_process
import redis
import pickle
pool = redis.ConnectionPool(host='127.0.0.1')
r = redis.Redis(connection_pool=pool)
oms="orderserver"
onoms="onorderserver"
def setredis(key,value):
    if isredis:
        r.set(key, pickle.dumps(value))
def setredis_map(name,key,data):
    if isredis:
        r.hset(name, key, pickle.dumps(data))
def setredis_mapall(name,data):
    if isredis:
        for k ,v in data.items():
            r.hset(name, k, pickle.dumps(v))
def getredis(key):
    if isredis:
        p=r.get(key)
        if p:
            return pickle.loads(p)
        else:
            return {}
    else:
        return {}
def getredis_map(name,key=""):
    if isredis:
        if key=="":
            p=r.hgetall(name)
            if p:
                ret={}
                for k,v in p.items():
                    k1=str(k,encoding="utf")
                    ret[k1]=pickle.loads(v)
                return ret
            else:
                return {}
        else:
            p=r.hget(name,key)
            if p:
                return pickle.loads(p)
            else:
                return {}
    else:
        return {}
def bytes2str(d):
    return str(d, encoding = "utf")
class chatat:
    def __init__(self,itchat):
        self.__itchat=itchat
    def dealcmd(self,msg,fromuser):
        msgs=msg.split()
        if msgs[0] in ["下单","下","trade","T","t","交易","买","卖"]:
            self.trade(msgs,fromuser)
        elif msgs[0] in ["查一下","查","查询","Q","q","qry","query"]:
            self.query(msgs,fromuser)
        elif msgs[0] in ["止损","设止损","stop","S","止"]:
            self.stop(msgs,fromuser)
        elif msgs[0] in ["请","设","set","令","cmd"]:
            self.cmd(msgs,fromuser)
        elif msgs[0] in ["查服务","c","C","check"]:
            self.check(msgs,fromuser)
        else:
            self.__itchat.send('%s?  不明白你说的： %s是什么意思' % (msgs[0], msg), fromuser)
            print("can not deal this:",msg)
    def check(self,msgs,fromuser):
        if len(msgs)!=1:
            name=msgs[1]
            self.__itchat.send('%s： %s' % (name, check_process(name)), fromuser)
            if len(msgs)>2:
                self.__itchat.send('%s： %s' % (name, get_process(name)), fromuser)
        else:
            self.__itchat.send('mongod: %s' % (check_process("mongod")), fromuser)
            self.__itchat.send('redis: %s' % (check_process("redis")), fromuser)
            self.__itchat.send('MoheServer: %s' % (check_process("MoheServer")), fromuser)
            self.__itchat.send('ssmanager: %s' % (check_process("ssmanager")), fromuser)
    def trade(self,msgs,fromuser):
        if len(msgs)==3:
            order={}
            if msgs[1] in ["buy","b","B","买","买入","买开","买平"]:
                order["bs"]='b'
            else:
                order["bs"]='s'
            order["obj"]=msgs[2]
            ret=mh.safesend_sync(oms,"bs",order)
            if ret["errcode"]==0:
                self.__itchat.send("已经发送", fromuser)
            else:
                self.__itchat.send("消息超时，发送失败", fromuser)
            print("order:",order)
        elif len(msgs)==4:
            order={}
            if msgs[1] in ["buy","b","B","买","买入","买开","买平"]:
                order["bs"]='b'
            else:
                order["bs"]='s'
            order["obj"]=msgs[2]
            order["qty"]=msgs[3]
            ret=mh.safesend_sync(oms,"order_market",order)
            if ret["errcode"]==0:
                self.__itchat.send("已经发送", fromuser)
            else:
                self.__itchat.send("消息超时，发送失败", fromuser)
            print("order:",order)
        elif len(msgs)==5:
            order={}
            if msgs[1] in ["buy","b","B","买","买入","买开","买平"]:
                order["bs"]='b'
            else:
                order["bs"]='s'
            order["obj"]=msgs[2]
            order["qty"]=msgs[3]
            order["price"]=msgs[4]
            ret=mh.safesend_sync(oms,"order_limit",order)
            if ret["errcode"]==0:
                self.__itchat.send("已经发送", fromuser)
            else:
                self.__itchat.send("消息超时，发送失败", fromuser)
            print("order:",order)
        else:
            self.__itchat.send('%s?  不明白,必须：操作方向 合约 数量 价格' % (msgs), fromuser)
            print("can not deal this:",msgs)
    def query(self,msgs,fromuser):
        if len(msgs)!=1:
            if isredis:
                if msgs[1] in ["行情","价格","价","p","price"]:
                    t=gettick(msgs[2])
                    if t:
                        t0={}
                        t0["时间"]=t["timekey"].strftime('%H:%M:%S.%f')
                        t0["最新价"]=t["LastPrice"]
                        t0["最新量"]=t["volume"]
                        t0["均价"]=t["AveragePrice"]
                        t0["卖1"]=t["AskPrice1"]
                        t0["卖1量"]=t["AskVolume1"]
                        t0["买1"]=t["BidPrice1"]
                        t0["买1量"]=t["BidVolume1"]
                        t0["开"]=t["OpenPrice"]
                        t0["高"]=t["HighestPrice"]
                        t0["低"]=t["LowestPrice"]
                        self.__itchat.send(json.dumps(t0,ensure_ascii=False), fromuser)
                    else:
                        self.__itchat.send('%s 没有行情' % (msgs[2]), fromuser)
                elif msgs[1] in ["资金","f","fund","F","账户","cash"]:
                    if len(msgs)>=3:
                        key=keyword.g_fund+msgs[2]
                        ret=getredis(key)
                        if ret:
                            self.__itchat.send(json.dumps(ret,ensure_ascii=False), fromuser)
                        else:
                            self.__itchat.send('%s 没有%s' % (msgs[2],msgs[1]), fromuser)
                    else:
                        rkey=r.keys(keyword.g_fund+"*")
                        if rkey:
                            for k in r.keys(keyword.g_fund+"*"):
                                self.__itchat.send(bytes2str(k), fromuser)
                                ret=getredis(k)
                                if ret:
                                    self.__itchat.send(json.dumps(ret,ensure_ascii=False), fromuser)
                                else:
                                    self.__itchat.send('%s 没有%s' % (k,msgs[1]), fromuser)
                        else:
                            self.__itchat.send('没有%s' % (msgs[1]), fromuser)
                elif msgs[1] in ["委托","订单","order","o","O"]:
                    if len(msgs)>=3:
                        key=keyword.g_order+msgs[2]
                        ret=getredis_map(key)
                        if ret:
                            for v in ret.values():
                                self.__itchat.send(json.dumps(v,ensure_ascii=False), fromuser)
                        else:
                            self.__itchat.send('%s 没有%s' % (msgs[2],msgs[1]), fromuser)
                    else:
                        rkey=r.keys(keyword.g_order+"*")
                        if rkey:
                            for k in r.keys(keyword.g_order+"*"):
                                self.__itchat.send(bytes2str(k), fromuser)
                                ret=getredis_map(k)
                                if ret:
                                    self.__itchat.send(json.dumps(ret,ensure_ascii=False), fromuser)
                                else:
                                    self.__itchat.send('%s 没有%s' % (k,msgs[1]), fromuser)
                        else:
                            self.__itchat.send('没有%s' % (msgs[1]), fromuser)
                elif msgs[1] in ["持仓","仓位","头寸","pos","p"]:
                    if len(msgs)>=3:
                        key=keyword.g_pos+msgs[2]
                        ret=getredis_map(key)
                        if ret:
                            for v in ret.values():
                                self.__itchat.send(json.dumps(v,ensure_ascii=False), fromuser)
                        else:
                            self.__itchat.send('%s 没有%s' % (msgs[2],msgs[1]), fromuser)
                    else:
                        rkey=r.keys(keyword.g_pos+"*")
                        if rkey:
                            for k in r.keys(keyword.g_pos+"*"):
                                mv=str(k, encoding = "utf")
                                print(k,mv)
                                self.__itchat.send(mv, fromuser)
                                ret=getredis_map(k)
                                if ret:
                                    self.__itchat.send(json.dumps(ret,ensure_ascii=False), fromuser)
                                else:
                                    self.__itchat.send('%s 没有%s' % (k,msgs[1]), fromuser)
                        else:
                            self.__itchat.send('没有%s' % (msgs[1]), fromuser)
                elif msgs[1] in ["结算单","结算"]:
                    if len(msgs)>=3:
                        key=keyword.ctp_settlinfo+msgs[2]
                        ret=getredis(key)
                        if ret:
                            self.__itchat.send(json.dumps(ret,ensure_ascii=False), fromuser)
                        else:
                            self.__itchat.send('%s 没有%s' % (msgs[2],msgs[1]), fromuser)
                    else:
                        rkey=r.keys(keyword.ctp_settlinfo+"*")
                        if rkey:
                            for k in r.keys(keyword.ctp_settlinfo+"*"):
                                self.__itchat.send(bytes2str(k), fromuser)
                                ret=getredis(k)
                                if ret:
                                    self.__itchat.send(json.dumps(ret,ensure_ascii=False), fromuser)
                                else:
                                    self.__itchat.send('%s 没有%s' % (k,msgs[1]), fromuser)
                        else:
                            self.__itchat.send('没有%s' % (msgs[1]), fromuser)
                else:
                    self.__itchat.send('%s?  不明白你说的： %s是什么意思' % (msgs[1], msgs), fromuser)
                    print("can not deal this:",msgs)
            else:
                self.__itchat.send('redis is not run', fromuser)
                print("can not deal this,redis is not run:",msgs)
        else:
            self.__itchat.send('查什么？' , fromuser)
            print("can not deal this:",msgs)
    def stop(self,msgs,fromuser):
        if msgs[1] in ["","","","",""]:
            pass
        elif msgs[1] in ["","","","",""]:
            pass
        elif msgs[1] in ["","","","",""]:
            pass
        elif msgs[1] in ["","","","",""]:
            pass
        else:
            self.__itchat.send('%s?  不明白你说的： %s是什么意思' % (msgs[1], msgs), fromuser)
            print("can not deal this:",msgs)
    def cmd(self,msgs,fromuser):
        if len(msgs)>2:
            if msgs[1] in ["shell","cmd","bash","sh","linux"]:
                cmds=" ".join(msgs[2:])
                ret=os.popen(cmds+" | grep -v grep").readlines()
                if ret:
                    for i in ret:
                        self.__itchat.send(i, fromuser)
                else:
                    self.__itchat.send('%s 没有内容' % (cmds), fromuser)
            elif msgs[1] in ["redis"]:
                pass
            elif msgs[1] in ["mongo"]:
                pass
            elif msgs[1] in ["msg","m","M","mh","mohe"]:
                t={}
                n=len(msgs)-3
                import math
                m=math.floor(n/2)
                for i in range(0,m):
                    t[msgs[4+i]]=msgs[5+i]
                ret=mh.safesend_sync(msgs[1],msgs[2],t)
                if ret["errcode"]==0:
                    self.__itchat.send("已经发送", fromuser)
                else:
                    self.__itchat.send("消息超时，发送失败", fromuser)
                print(msgs[1],msgs[2],t)
            else:
                self.__itchat.send('%s?  不明白你说的： %s是什么意思' % (msgs[1], msgs), fromuser)
                print("can not deal this:",msgs)
        else:
            self.__itchat.send('%s?  不明白,检查您的命令' % (msgs), fromuser)
            print("can not deal this:",msgs)
